/**
 * GenericServlet.java
 *
 * Copyright (c) 2009 viorelt All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of viorelt .
 **/
package ro.prjmanager.core.list;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import ro.prjmanager.core.annotations.List;
import ro.prjmanager.core.service.Service;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

public class GenericServlet extends HttpServlet {
    public static final Log log = LogFactoryImpl.getLog(GenericServlet.class);

    protected ApplicationContext getSpringContext(HttpServletRequest request) {
        return WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
    }

    protected Service getService(HttpServletRequest request,String serviceName){
       return (Service) getSpringContext(request).getBean(serviceName);
    }


    protected Service getServiceList(HttpServletRequest request) {
        RequestParamList rpl = new RequestParamList(request);
        Service service = null;
        try {
            Class clazz = Class.forName(rpl.getClassModel());
            List list = clazz.newInstance().getClass().getAnnotation(ro.prjmanager.core.annotations.List.class);
            String serviceName = list.serviceName();
            service = (Service) getSpringContext(request).getBean(serviceName);
        } catch (ClassNotFoundException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (InstantiationException e) {
            log.error(e);
        }
        return service;
    }
}
